//
//  MCCoreDataApplicationDelegate.m
//  MCToolbox
//
//  Created by J. G. Pusey on 10/25/10.
//  Copyright 2010 MedCommons, Inc. All rights reserved.
//
//  Redistribution and use in source and binary forms, with or without
//  modification, are permitted provided that the following conditions are
//  met:
//
//  * Redistributions of source code must retain the above copyright notice,
//    this list of conditions and the following disclaimer.
//  * Redistributions in binary form must reproduce the above copyright
//    notice, this list of conditions and the following disclaimer in the
//    documentation and/or other materials provided with the distribution.
//  * Neither the name of MedCommons, Inc. nor the names of its contributors
//    may be used to endorse or promote products derived from this software
//    without specific prior written permission.
//
//  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
//  IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
//  THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
//  PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
//  CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
//  EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
//  PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
//  PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
//  LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
//  NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
//  SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//

#import "MCCoreDataApplicationDelegate.h"
#import "NSDictionary+MCToolbox.h"

#pragma mark -
#pragma mark Public Class MCCoreDataApplicationDelegate
#pragma mark -

//@interface MCCoreDataApplicationDelegate ()
//
//@end

@implementation MCCoreDataApplicationDelegate

@dynamic applicationName;
@dynamic documentsDirectory;
@dynamic managedObjectContext;
@dynamic managedObjectModel;
@dynamic modelFileURL;
@dynamic persistentStoreCoordinator;
@dynamic persistentStoreURL;

#pragma mark Public Instance Methods

- (NSString *) applicationName
{
    return [[[NSBundle mainBundle] infoDictionary]
            stringForKey: @"CFBundleName"];
}

- (NSString *) documentsDirectory
{
    return [NSSearchPathForDirectoriesInDomains (NSDocumentDirectory,
                                                 NSUserDomainMask,
                                                 YES)
            lastObject];
}

/**
 * Returns the managed object context for the application. If the context
 * doesn't already exist, it is created and bound to the persistent store
 * coordinator for the application.
 */
- (NSManagedObjectContext *) managedObjectContext
{
    if (!self->managedObjectContext_)
    {
        NSPersistentStoreCoordinator *psc = self.persistentStoreCoordinator;

        if (psc)
        {
            self->managedObjectContext_ = [NSManagedObjectContext new];

            [self->managedObjectContext_ setPersistentStoreCoordinator: psc];
        }
    }

    return self->managedObjectContext_;
}

/**
 * Returns the managed object model for the application. If the model doesn't
 * already exist, it is created from the application's model.
 */
- (NSManagedObjectModel *) managedObjectModel
{
    if (!self->managedObjectModel_)
        self->managedObjectModel_ = [[NSManagedObjectModel alloc]
                                     initWithContentsOfURL: self.modelFileURL];

    return self->managedObjectModel_;
}

- (NSURL *) modelFileURL
{
    NSString *modelPath = [[NSBundle mainBundle] pathForResource: self.applicationName
                                                          ofType: @"momd"];

    return [NSURL fileURLWithPath: modelPath];
}

/**
 * Returns the persistent store coordinator for the application. If the
 * coordinator doesn't already exist, it is created and the application's
 * store added to it.
 */
- (NSPersistentStoreCoordinator *) persistentStoreCoordinator
{
    if (!self->persistentStoreCoordinator_)
    {
        self->persistentStoreCoordinator_ = [[NSPersistentStoreCoordinator alloc]
                                             initWithManagedObjectModel: self.managedObjectModel];

        NSURL *storeURL = self.persistentStoreURL;

        if (storeURL)
        {
            NSError *error = nil;

            if (![self->persistentStoreCoordinator_ addPersistentStoreWithType: NSSQLiteStoreType
                                                                 configuration: nil
                                                                           URL: storeURL
                                                                       options: nil
                                                                         error: &error])
            {
                /*
                 Replace this implementation with code to handle the error appropriately.

                 abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. If it is not possible to recover from the error, display an alert panel that instructs the user to quit the application by pressing the Home button.

                 Typical reasons for an error here include:
                 * The persistent store is not accessible;
                 * The schema for the persistent store is incompatible with current managed object model.
                 Check the error message to determine what the actual problem was.

                 If the persistent store is not accessible, there is typically something wrong with the file path. Often, a file URL is pointing into the application's resources directory instead of a writeable directory.

                 If you encounter schema incompatibility errors during development, you can reduce their frequency by:
                 * Simply deleting the existing store:
                 [[NSFileManager defaultManager] removeItemAtURL:storeURL error:nil]

                 * Performing automatic lightweight migration by passing the following dictionary as the options parameter:
                 [NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithBool:YES],NSMigratePersistentStoresAutomaticallyOption, [NSNumber numberWithBool:YES], NSInferMappingModelAutomaticallyOption, nil];

                 Lightweight migration will only work for a limited set of schema changes; consult "Core Data Model Versioning and Data Migration Programming Guide" for details.

                 */
                NSLog (@"Unresolved error %@, %@",
                       error,
                       [error userInfo]);

                abort ();
            }
        }
    }

    return self->persistentStoreCoordinator_;
}

- (NSURL *) persistentStoreURL
{
    NSString *tmpPath = [self.documentsDirectory stringByAppendingPathComponent:
                         [NSString stringWithFormat:
                          @"%@.sqlite",
                          self.applicationName]];

    return [NSURL fileURLWithPath: tmpPath];
}

#pragma mark Overridden NSObject Instance Methods

- (void) dealloc
{
    [self->managedObjectContext_ release];
    [self->managedObjectModel_ release];
    [self->persistentStoreCoordinator_ release];

    [super dealloc];
}

@end
